import io
import os

from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QPushButton, QLabel, QHBoxLayout, QWidget, QListWidget

from LanguageTool import getCNfromDict
from VideoTool import readMP3, readSpeedMP3, readGainMP3, getMP3data, getMP3_frame_rate, playMP3, \
    getMP3Size, readPCM, readSpeedPCM, getPCMdata, readGainPCM, getPCMSize, readBIN, readSpeedBIN, getBINdata, \
    readGainBIN, getBINSize, outputMP3, outputPCM, outputBIN
from mylog import addLog


class AudioprocessingWidget(QWidget):
    file_path = ""
    status = 0
    fmt = ""

    speed = 1.00    # 播放速度
    gain = 0.0      # 增益

    size = 0

    hz = 0

    # mp3
    audio = None        # 原始音频
    speedAudio = None   # 原始音频，倍速后
    gainAudio = None    # 原始音频，倍速后，增益后
    cropAudio = None    # 原始音频，倍速后，增益后，裁剪后

    totolTime = 0  # 倍速后，音频时长，单位ms
    start_ms = 0
    end_ms = 0

    audio_data = None   # 倍速后，归一化后的波形数据

    del_signal = pyqtSignal(int)

    def __init__(self, file_path, list_widget, progress_dialog, parent=None):
        super().__init__(parent)

        self.file_path = file_path
        self.list_widget = list_widget

        # 分割出目录、文件名和扩展名
        directory, file_name = os.path.split(self.file_path)
        file_base, file_ext = os.path.splitext(file_name)
        self.fmt = file_ext.upper()

        layout = QHBoxLayout()
        layout.setContentsMargins(5, 5, 5, 5)

        # 状态信息
        self.status_label = QLabel('')
        self.status_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.setStatus(self.status)
        layout.addWidget(self.status_label)

        # 左侧显示文件路径
        path_label = QLabel(file_path)
        path_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        layout.addWidget(path_label)

        # 添加伸缩因子，将标签靠左
        layout.addStretch(1)

        # 右侧删除按钮
        self.del_button = QPushButton(getCNfromDict('TabBar01-tb1-delbtn'), self)
        self.del_button.clicked.connect(self.del_button_clicked)  # 按钮事件绑定
        self.del_button.setFixedWidth(100)
        layout.addWidget(self.del_button)

        # 设置布局
        self.setLayout(layout)

        progress_dialog.update_progress(20)
        # 装载数据
        self.loadAudio()
        progress_dialog.update_progress(50)
        self.loadSpeedAudio()
        progress_dialog.update_progress(70)
        self.loadGainAudio()
        progress_dialog.update_progress(90)
        self.loadCropAudio()
        progress_dialog.update_progress(100)
        progress_dialog.update_status(1)

    def loadAudio(self):
        if 'MP3' in self.fmt:
            self.audio = readMP3(self.file_path)
            self.hz = getMP3_frame_rate(self.audio)
            # print(getMP3_frame_rate(self.audio))
        elif 'PCM' in self.fmt:
            self.audio = readPCM(self.file_path)
            self.hz = 44100
        elif 'BIN' in self.fmt:
            self.audio = readBIN(self.file_path)
            self.hz = 22050

    def loadSpeedAudio(self):
        if 'MP3' in self.fmt:
            # print(f"原音频时长：{len(self.audio)}s")
            self.speedAudio = readSpeedMP3(self.audio, self.speed)

            self.totolTime = len(self.speedAudio)

            self.start_ms = 0
            self.end_ms = self.totolTime
            self.audio_data = getMP3data(self.speedAudio)
        elif 'PCM' in self.fmt:
            self.speedAudio = readSpeedPCM(self.audio, self.speed)
            self.totolTime = len(self.speedAudio)
            self.start_ms = 0
            self.end_ms = self.totolTime
            self.audio_data = getPCMdata(self.speedAudio)
        elif 'BIN' in self.fmt:
            self.speedAudio = readSpeedBIN(self.audio, self.speed)
            self.totolTime = len(self.speedAudio)
            self.start_ms = 0
            self.end_ms = self.totolTime
            self.audio_data = getBINdata(self.speedAudio)

    def loadGainAudio(self):
        if 'MP3' in self.fmt:
            self.gainAudio = readGainMP3(self.speedAudio, self.gain)
        elif 'PCM' in self.fmt:
            self.gainAudio = readGainPCM(self.speedAudio, self.gain)
        elif 'BIN' in self.fmt:
            self.gainAudio = readGainBIN(self.speedAudio, self.gain)

    def loadCropAudio(self):
        if 'MP3' in self.fmt:
            self.cropAudio = self.gainAudio[self.start_ms: self.end_ms]
        elif 'PCM' in self.fmt:
            self.cropAudio = self.gainAudio[self.start_ms: self.end_ms]
        elif 'BIN' in self.fmt:
            self.cropAudio = self.gainAudio[self.start_ms: self.end_ms]

    def playCropAudio(self):
        if 'MP3' in self.fmt:
            playMP3(self.cropAudio)
        elif 'PCM' in self.fmt:
            playMP3(self.cropAudio)
        elif 'BIN' in self.fmt:
            playMP3(self.cropAudio)

    def del_button_clicked(self):
        """
        删除当前项
        """
        addLog('AudioprocessingWidget', 'info', f"del_button_clicked")

        # 通过小部件找到对应的 QListWidgetItem
        for index in range(self.list_widget.count()):
            item = self.list_widget.item(index)
            if self.list_widget.itemWidget(item) is self:
                # 删除该项
                addLog('AudioprocessingWidget', 'info', f"del {self.file_path}")
                self.del_signal.emit(index)
                self.list_widget.takeItem(index)
                break

    def getPath(self):
        return self.file_path

    def setStatus(self, status):
        self.status = status
        if status == 1:
            self.status_label.setText('已完成')
            self.status_label.setStyleSheet('color: blue')
        elif status == 0:
            self.status_label.setText('待执行')
            self.status_label.setStyleSheet('color: gray')
        elif status == 2:
            self.status_label.setText('失败')
            self.status_label.setStyleSheet('color: red')

    def getStatus(self):
        return self.status

    def getFmt(self):
        return self.fmt

    def setSpeed(self, speed):
        self.speed = speed
        self.setStatus(0)

    def getSpeed(self):
        return self.speed

    def setGain(self, gain):
        self.gain = gain
        self.setStatus(0)

    def getGain(self):
        return self.gain

    def getData(self):
        return self.audio_data

    def getTotleTime(self):
        return self.totolTime

    def getStartTime(self):
        return self.start_ms

    def setStartTime(self, start_ms):
        self.start_ms = start_ms
        self.setStatus(0)

    def getEndTime(self):
        return self.end_ms

    def setEndTime(self, end_ms):
        self.end_ms = end_ms
        self.setStatus(0)

    def getSize(self):
        # 预测文件大小
        if 'MP3' in self.fmt:
            return getMP3Size(self.cropAudio)
        elif 'PCM' in self.fmt:
            return getPCMSize(self.cropAudio)
        elif 'BIN' in self.fmt:
            return getBINSize(self.cropAudio)

    def getHz(self):
        return self.hz

    def output(self):
        # 保存处理后的文件
        # 分割出目录、文件名和扩展名
        directory, file_name = os.path.split(self.file_path)
        outputFile = "./AudioProcess/"+file_name
        if 'MP3' in self.fmt:
            return outputMP3(self.cropAudio, outputFile)
        elif 'PCM' in self.fmt:
            return outputPCM(self.cropAudio, outputFile)
        elif 'BIN' in self.fmt:
            return outputBIN(self.cropAudio, outputFile)

